%==========================================================================
%%  VAR 3 Variables, First Differences, Cholesky Identification,
%  Appendix Figure A3
%==========================================================================


clc; clear all; close all;
rng default
set(0,'defaulttextfontsize',17); 
set(0,'defaultaxesfontsize',17); 
set(0,'defaultlinelinewidth',2);
ifig=1;


%% Cholesky SVAR.(lnGDP_d1,D1HHD_GDP,D1FD_GDP)


%% (0) Prepare Data 
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[STATA]=csvread('VAR3_lnGDPd1_D1HHDGDP_D1NFDGDP.csv');
I_Y = 3:1:5; I_X = 6:1:size(STATA,2);                            
cc            = STATA(:,1);                                                
[VAR.Ti,VAR.ii]= histc(cc,unique(cc));                                    
VAR.Y         = STATA(:,I_Y); 
VAR.X         = STATA(:,I_X);                                         
VAR.p         = 5;                                                     
VAR.irhor     = 11;                                                     
VAR.h         = 0:1:(VAR.irhor-1);
VAR.N         = max(VAR.ii);                                             
VAR.Perm      = [1 0 0; 0 0 1 ; 0 1 0];                                 
VAR.normalize = 1;
VAR.Year      = STATA(:,2);
clevel        = [95 ; 90];


%% (1) Estimate RF VAR
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
VAR       = rfvar(VAR);
VAR_Chol  = irfvar(VAR);



%% (2) Bootstrap CIs for IRF
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

nboot= 2000;
VAR_Chol_bs = doCholVARbootstrap_CS(VAR,nboot,clevel);
h   =VAR.h;
% Fig: IRF with bootstrapped CIs: HHD->y, NFD->y. CUMULATIVE
cholIRF_cum   = cumsum(VAR_Chol.cholIRF,1);
figure(ifig); 
subplot(1,3,1); plot(h,cholIRF_cum(:,1,1),'o-k',h,VAR_Chol_bs.CholirsCumH1(:,1,1),'--k',h,VAR_Chol_bs.CholirsCumL1(:,1,1),'--k'); 
title('\Delta d^{HH} \rightarrow  \Delta d^{HH}');
subplot(1,3,2); plot(h,cholIRF_cum(:,1,2),'o-k',h,VAR_Chol_bs.CholirsCumH1(:,1,2),'--k',h,VAR_Chol_bs.CholirsCumL1(:,1,2),'--k'); 
title('\Delta d^{HH} \rightarrow  \Delta y'); xlabel('Years after impulse');
subplot(1,3,3); plot(h,cholIRF_cum(:,1,3),'o-k',h,VAR_Chol_bs.CholirsCumH1(:,1,3),'--k',h,VAR_Chol_bs.CholirsCumL1(:,1,3),'--k'); 
title('\Delta d^F \rightarrow  \Delta y'); 
axis([0 10 -1.4 0.6]); 
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 1 .55]);
ifig=ifig+1;




